import Vue from 'vue'
import VueRouter from 'vue-router'

import Login from '@/views/Login.vue'
import Register from '@/views/Register.vue'
import Detail from '@/views/Detail.vue'
import Home from '@/views/Home.vue'
import Article from '@/views/Layout/Article.vue'
import Collect from '@/views/Layout/Collect.vue'
import Like from '@/views/Layout/Like.vue'
import User from '@/views/Layout/User.vue'

Vue.use(VueRouter)

const routes = [
  { path: '/login', component: Login },
  { path: '/register', component: Register },
  { path: '/detail/:id', component: Detail },
  {
    path: '/',
    // 利用重定向，展示初始页面
    redirect: 'login',
    component: Home,
    children: [
      { path: 'article', component: Article },
      { path: 'collect', component: Collect },
      { path: 'like', component: Like },
      { path: 'user', component: User }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 这里加入导航守卫（全局设置）
router.beforeEach((to, from, next) => {
  // 访问任何地址，都会执行这个函数
  // -to 表示你要访问那个页面，to.path表示你要访问的路由路径
  // -from 表示你哪里跳转过来的
  // -next() --允许通过；next('/login') --表示不允许通过，跳转至登录页
  if (
    !localStorage.getItem('mobile-token') &&
    to.path !== '/login' &&
    to.path !== '/register'
  ) {
    next('/login') // 跳转到登录页
    return
  }
  next() // 不符合上述条件，允许通过
})

export default router
